package utils
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	
	import framework.AppGlobal;

	public class ImageUtil
	{
		/**
		 * 图片加载，包括SWF
		 * @param p_filePath
		 * @param p_callback 文件加载完成后回调函数，具有一个参数，参数类型是DisplayObject
		 */
		public static function loadImg(p_filePath:String, p_callback:Function):void
		{
			if(p_filePath.indexOf("http://") < 0)
				p_filePath = AppGlobal.contextRoot + p_filePath;
			var urlReq:URLRequest = new URLRequest(p_filePath);
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadCompleteHandler);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			loader.load(urlReq);
			//加载完成
			function loadCompleteHandler(p_evt:Event):void
			{
				var li:LoaderInfo = p_evt.currentTarget as LoaderInfo;
				removeEvtListener(li);
				if(p_callback != null)
					p_callback(li.content);
			}
			//读取文件失败
			function ioErrorHandler(p_evt:IOErrorEvent):void
			{
				removeEvtListener(p_evt.currentTarget as LoaderInfo);
				trace("load file fail!" + p_evt.text);
			}
			//移除事件
			function removeEvtListener(p_target:LoaderInfo):void
			{
				p_target.removeEventListener(Event.COMPLETE, loadCompleteHandler);
				p_target.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			}
		}
	}
}